package com.ruoyi.web.controller.wechat;

import com.ruoyi.by.health.component.EmpWeChatTokenService;
import com.ruoyi.by.health.domain.WechatLoginEmp;
import com.ruoyi.by.health.domain.entity.ByhealthEmployee;
import com.ruoyi.by.health.domain.entity.ByhealthLotteryOutcome;
import com.ruoyi.by.health.domain.entity.EmployeeMessageWall;
import com.ruoyi.by.health.domain.form.ByhealthEmployeeParam;
import com.ruoyi.by.health.domain.form.EmployeeGameForm;
import com.ruoyi.by.health.domain.form.PlaybillVoteForm;
import com.ruoyi.by.health.domain.form.SystemConfigParam;
import com.ruoyi.by.health.domain.vo.EmployeeGameListVo;
import com.ruoyi.by.health.domain.vo.EmployeeGameVo;
import com.ruoyi.by.health.service.IByhealthEmployeeService;
import com.ruoyi.by.health.service.IByhealthLotteryOutcomeService;
import com.ruoyi.by.health.service.IByhealthPlaybillService;
import com.ruoyi.by.health.service.IEmployeeMessageWallService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author cj
 */
@Api(value = "员工微信接口", tags = "员工微信接口")
@RestController
@RequestMapping("/wechat/emp")
public class WeChatEmpController extends BaseController {

    @Autowired
    private IByhealthEmployeeService employeeService;
    @Autowired
    private IEmployeeMessageWallService messageService;
    @Autowired
    private IByhealthPlaybillService playbillService;
    @Autowired
    private EmpWeChatTokenService empWeChatTokenService;
    @Resource
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    IByhealthLotteryOutcomeService lotteryOutcomeService;

    private static final Logger log = LoggerFactory.getLogger(WeChatEmpController.class);


    /**
     * 获取小程序配置信息
     *
     * @return 小程序配置信息
     */
    @ApiOperation("获取小程序配置信息")
    @GetMapping("getConfigList")
    public AjaxResult getConfigList() {
        Map<Object, Object> entries = redisTemplate.opsForHash().entries("byhealth_system_config");
        return AjaxResult.success(entries);
    }

    /**
     * 更新小程序配置信息
     *
     * @return 更新小程序配置信息
     */
    @ApiOperation("更新小程序配置信息")
    @PostMapping("updateConfig")
    public AjaxResult updateConfig(@RequestBody SystemConfigParam configParam) {

        redisTemplate.opsForHash().put("byhealth_system_config", configParam.getKey(), configParam.getValue());

        return AjaxResult.success();
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation("获取小程序登录信息")
    @GetMapping("getAppInfo")
    public AjaxResult getInfo(HttpServletRequest request) {
        WechatLoginEmp loginEmp = empWeChatTokenService.getLoginUser(request);
        if (Objects.isNull(loginEmp)) {
            return AjaxResult.error(2, "登录信息失效，请重新登录！");
        }
        ByhealthEmployee newEmp =  employeeService.selectEmployeeByEmpId(loginEmp.getEmpId());
        loginEmp.setEmployee(newEmp);
        List<ByhealthLotteryOutcome> lotteryOutcomeList = lotteryOutcomeService.getLotteryOutcomeByEmpId(newEmp.getEmpId());
        loginEmp.setLotteryOutcomes(lotteryOutcomeList);
        empWeChatTokenService.refreshToken(loginEmp);

        return AjaxResult.success(loginEmp);
    }

    @ApiOperation("保存员工游戏得分")
    @PostMapping("/gameScore")
    public AjaxResult gameScore(@RequestBody EmployeeGameForm gameForm, HttpServletRequest request) {
        WechatLoginEmp loginEmp = empWeChatTokenService.getLoginUser(request);
        if (Objects.isNull(loginEmp)) {
            return AjaxResult.error(2,"登录信息失效，请重新登录！");
        }
        Object gameEndTimeObject = redisTemplate.opsForHash().get("byhealth_system_config", "gameEndTime");
        if (Objects.isNull(gameEndTimeObject)) {
            return AjaxResult.error("游戏结束时间未设置，请联系管理员！");
        }
        LocalDateTime gameEndTime = LocalDateTime.parse(gameEndTimeObject.toString());
        if (LocalDateTime.now().isAfter(gameEndTime)) {
            return AjaxResult.error("游戏结束时间已结束！");
        }


        if (Objects.nonNull(loginEmp.getEmployee().getIsTest())) {
            if(loginEmp.getEmployee().getIsTest()==1){
                return AjaxResult.success();
            }
        } else {
            return AjaxResult.error(2,"登录信息失效，请重新登录！");
        }
        gameForm.setEmpId(loginEmp.getEmpId());
        return employeeService.gameScore(gameForm);
    }

    @ApiOperation("获取员工游戏得分排行榜")
    @GetMapping("/gameScoreList")
    public AjaxResult gameScoreList(EmployeeGameForm gameForm, HttpServletRequest request) {
        WechatLoginEmp loginEmp = empWeChatTokenService.getLoginUser(request);
        if (Objects.isNull(loginEmp)) {
            return AjaxResult.error(2,"登录信息失效，请重新登录！");
        }
        gameForm.setEmpId(loginEmp.getEmpId());
        startPage();
        List<EmployeeGameVo> employeeGameVoList = employeeService.gameScoreList(gameForm);
        TableDataInfo dataInfo = getDataTable(employeeGameVoList);
        ByhealthEmployee employeeVo = employeeService.selectEmployeeByEmpId(loginEmp.getEmpId());
        EmployeeGameVo employeeGameVo = new EmployeeGameVo();
        BeanUtils.copyProperties(employeeVo, employeeGameVo);
        EmployeeGameListVo employeeGameListVo = new EmployeeGameListVo();
        employeeGameListVo.setGameVo(employeeGameVo);
        employeeGameListVo.setDataInfo(dataInfo);
        return AjaxResult.success(employeeGameListVo);
    }

    @ApiOperation("留言墙留言")
    @PostMapping("/addMessage")
    public AjaxResult gameScore(@RequestBody EmployeeMessageWall employeeMessage, HttpServletRequest request) {
        WechatLoginEmp loginEmp = empWeChatTokenService.getLoginUser(request);
        if (Objects.isNull(loginEmp)) {
            return AjaxResult.error(2,"登录信息失效，请重新登录！");
        }
        messageService.saveEmployeeMessage(employeeMessage, loginEmp);
        return AjaxResult.success("保存成功");
    }

    @ApiOperation("投票")
    @PostMapping("/vote")
    public AjaxResult vote(@RequestBody PlaybillVoteForm playbillVoteForm, HttpServletRequest request) {

        Object canVoteObj = redisTemplate.opsForHash().get("byhealth_system_config", "canVote");
        if (Objects.isNull(canVoteObj)) {
            return AjaxResult.error("投票开关未设置，请联系管理员！");
        }
        Boolean canVote = Boolean.valueOf(canVoteObj.toString());
        if (!canVote) {
            return AjaxResult.error("不允许投票！");
        }
        WechatLoginEmp loginEmp = empWeChatTokenService.getLoginUser(request);
        if (Objects.isNull(loginEmp)) {
            return AjaxResult.error(2,"登录信息失效，请重新登录！");
        }
        playbillVoteForm.setEmpId(loginEmp.getEmpId());
        return playbillService.vote(playbillVoteForm);
    }

    /**
     * 获取节目列表
     *
     * @return 获取节目列表
     */
    @ApiOperation("获取节目列表")
    @GetMapping("getPlaybillList")
    public AjaxResult getPlaybillList( HttpServletRequest request) {
        WechatLoginEmp loginEmp = empWeChatTokenService.getLoginUser(request);
        if (Objects.isNull(loginEmp)) {
            return AjaxResult.error(2,"登录信息失效，请重新登录！");
        }
        return AjaxResult.success(playbillService.selectPlaybillListByEmpId(loginEmp.getEmpId()));
    }


    /**
     * 更新地址信息
     *
     * @return 更新地址信息
     */
    @ApiOperation("更新地址信息")
    @PostMapping("updateEmpAddress")
    public AjaxResult updateEmpAddress(@RequestBody ByhealthEmployeeParam addressParam, HttpServletRequest request) {

        WechatLoginEmp loginEmp = empWeChatTokenService.getLoginUser(request);
        if (Objects.isNull(loginEmp)) {
            return AjaxResult.error(2, "登录信息失效，请重新登录！");
        }
        ByhealthEmployee emp = new ByhealthEmployee();
        emp.setEmpId(loginEmp.getEmpId());
        emp.setEmpAddress(addressParam.getEmpAddress());
        emp.setEmpAddressPcd(addressParam.getEmpAddressPcd());
        emp.setRecipientName(addressParam.getRecipientName());
        emp.setRecipientPhone(addressParam.getRecipientPhone());
        employeeService.updateEmployee(emp);
        ByhealthEmployee newEmp =  employeeService.selectEmployeeByEmpId(loginEmp.getEmpId());
        loginEmp.setEmployee(newEmp);
        empWeChatTokenService.refreshToken(loginEmp);
        return AjaxResult.success();
    }
}
